//
//  SYComposeView.swift
//  SYWeibo
//
//  Created by Saya on 16/4/15.
//  Copyright © 2016年 黄金果. All rights reserved.
//

import UIKit

class SYComposeView: UIView {
    var targer:UIViewController?
    private lazy var composeBtns:[SYComposeBtn] = [SYComposeBtn]()
    private var composeArray:[SYComposeModel]?
    
    func show(targetVC:UIViewController){
        self.targer = targetVC
        targer?.view.addSubview(self)
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
//        self.removeFromSuperview()
        
        for (index,value) in composeBtns.reverse().enumerate() {
            UIView.animateWithDuration(5, delay: Double(index)*0.25, usingSpringWithDamping: 0.6, initialSpringVelocity: 3, options: [], animations: { () -> Void in
                if let tempBtn:SYComposeBtn = value {
                    tempBtn.center = CGPoint(x: tempBtn.center.x, y: tempBtn.center.y + 350)
                }
                }) { (_) -> Void in
                    self.removeFromSuperview()
            }
        }
    }
    
    //在view将要加到父视图的时候给按钮添加动画
    override func willMoveToSuperview(newSuperview: UIView?) {
        superview?.willMoveToSuperview(newSuperview)
        
        for (index,value) in composeBtns.enumerate() {
            UIView.animateWithDuration(2, delay: Double(index)*0.05, usingSpringWithDamping: 0.8, initialSpringVelocity: 7
                , options: [], animations: { () -> Void in
                if let tempBtn:SYComposeBtn = value {
                    tempBtn.center = CGPoint(x: tempBtn.center.x, y: tempBtn.center.y - 350)
                }
                }) { (_) -> Void in
                    
            }
        }
    }
    
    //MARK:界面设置
    override init(frame: CGRect) {
        let rect = UIScreen.mainScreen().bounds
        super.init(frame: rect)
        setUpUI()
    }
    
    private func setUpUI(){
        addSubview(backgroudImg)
        addSubview(adImage)
        
        backgroudImg.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.snp_edges)
        }
        adImage.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX)
            make.top.equalTo(self.snp_top).offset(110)
        }
        
        loadBtnSource()
        setBtns()
    }
    
    private func setBtns(){
//        let btnCount:CGFloat = CGFloat((composeArray?.count)!)
        let width:CGFloat = 80
        let height:CGFloat = 110
        let countInRow:Int = 3
        let margin:CGFloat = (screenWidth - CGFloat(countInRow)*width) / (CGFloat(countInRow)+1)
        //创建按键
        for i in 0 ..< composeArray!.count{
            let model:SYComposeModel = composeArray![i]
            
            //九宫格算法
            let row:Int = i / countInRow
            let col:Int = i % countInRow
            
            let x:CGFloat = margin+(margin+width)*CGFloat(col)
            let y:CGFloat = (margin+height)*CGFloat(row) + screenHeight//在屏幕的世界中y轴向下为正,x轴向右为正

            let baseRect:CGRect = CGRect(x: 0, y: 0, width: width, height: height)
            let frameOfBtn:CGRect = CGRectOffset(baseRect, x, y)
            let btn:SYComposeBtn = SYComposeBtn()
//            let btn:SYComposeBtn = SYComposeBtn(iconImage: UIImage(named: model.icon!)!, title: model.title!, frame: frameOfBtn, model: model)
            btn.model = model
            btn.frame = frameOfBtn
            
            addSubview(btn)
            
            btn.addTarget(self, action: "btnDidClick:", forControlEvents: .TouchUpInside)
            
            composeBtns.append(btn)
        }
        
    }
    
    @objc private func btnDidClick(sender:SYComposeBtn){
//        print(sender)
        var scale:CGFloat = 0
        for btn in composeBtns {
            if btn == sender {
                scale = 1.5
            }else{
                scale = 0.5
            }
            
            UIView.animateWithDuration(0.8, animations: { () -> Void in
//                    btn.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
                    btn.transform = CGAffineTransformMakeScale(scale, scale)
                    btn.alpha = 0
                }, completion: { (_) -> Void in
                    print("ok")
            })
        }
        //跳转到对应的控制器
        let classType = NSClassFromString(sender.model!.target!) as! UIViewController.Type
        let vc = classType.init()
        let nav = UINavigationController(rootViewController: vc)
        self.targer?.presentViewController(nav, animated: true, completion: { () -> Void in
            self.removeFromSuperview()
        })
    }
    

    private lazy var backgroudImg :UIImageView = UIImageView(image: UIImage.snapshotScreen().applyLightEffect())
    private lazy var adImage:UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func loadBtnSource(){
        let path:String = NSBundle.mainBundle().pathForResource("Compose.plist", ofType: nil)!
        let tempArray = NSArray(contentsOfFile: path) as! [[String:String]]
        //        print(tempArray)
        var arrayMutable:[SYComposeModel] = [SYComposeModel]()
        for dict in tempArray {
            let model:SYComposeModel = SYComposeModel(dict: dict)
            arrayMutable.append(model)
        }
        composeArray = arrayMutable
    }

    
}
